{% load i18n %}
$("#group-member-add, #group-admin-add").click(function() {
    var form = $("#member-add-form");
    form.modal({appendTo: "#main", focus:false});
    $('#simplemodal-container').css({'height':'auto', 'padding':0});
    $('#member-add-tabs').tabs();
    if ($(this).attr('id') == 'group-admin-add') {
        $('.hd', form).html("{% trans "Add administrators"%}");
        $('#enter .tip').addClass('hide');
        form.data('post_url', '{% url 'group_add_admin' group.id %}');
    } else {
        form.data('post_url', '{% url 'group_add_member' group.id %}');
    }
    addAutocomplete('#added-member-name', '#enter', contact_list);
});

$('#member-add-form').submit(function() {
    var form = $(this),
        cur_tab_id = $('.ui-tabs-selected a', form).attr('href'),
        post_data = '',
        input = $('[name="user_name"]', form); 
        switch(cur_tab_id) {
            case '#enter':
                post_data = input.val();
                break;
            case '#contact-options':
                $(cur_tab_id + ' .checkbox-checked .checkbox-orig').each(function() {
                    post_data += $(this).val() + ','; 
                });  
                input.val(post_data);
        }    
        if (!post_data) {
            apply_form_error(form.attr('id'), "{% trans "Please enter emails, or select some." %}");
            return false;
        }    

    var submit_btn = $('[type="submit"]', form);
    disable(submit_btn);
    $.ajax({
        url: form.data('post_url'),
        type: 'POST',
        dataType: 'json',
        cache: false,
        beforeSend: prepareCSRFToken,
        data: {
            'user_name': post_data
        },
        success: function(data) {
            location.reload(true);
        },
        error: function(data, textStatus, jqXHR) {
            var errors = $.parseJSON(data.responseText);
            $.each(errors, function(index, value) {
                apply_form_error(form.attr('id'), value);
            });
            enable(submit_btn);
        }
    });

    return false;
});
